<template>
  <div class="node_setting">
    <div class="setting_title">新指标配置</div>
    <div class="setting_item">
      <el-form :model="form">
        <el-form-item class="table_infinite_list">
          <el-table
            ref="tableRefDimension"
            class="infinite-list-item"
            :data="form.publicDimensionList"
            height="250"
            style="width: 100%"
            :row-key="(row) => row.id"
            :reserve-selection="true"
            border
            @selection-change="handleDimensionSelectChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="dimensionColumn" label="公有维度" />
          </el-table>
        </el-form-item>
        <el-form-item class="table_infinite_list">
          <el-table
            ref="tableRefTime"
            class="infinite-list-item"
            :data="form.timePeriodTableData"
            height="450"
            style="width: 100%"
            :row-key="(row) => row.id"
            :reserve-selection="true"
            border
            @selection-change="handleTimeSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column fixed prop="timeColumn" label="数据期列" />
          </el-table>
        </el-form-item>
      </el-form>
    </div>
    <!-- <el-button type="primary" size="large" @click="saveData">保存</el-button> -->
  </div>
</template>
<script lang="ts">
export default { name: "IndicatorConfigSetting" };
</script>
<script setup lang="ts">
import LogicFlow from "@logicflow/core";
import { MyLogicFlowPropertiesType } from "@/types/logic-flow";
import IndicatorThemeTableAPI, {
  IndciatorDimension,
  IndciatorTimePeriodListResponse,
  IndicatorIds,
} from "@/api/themeTable/index";

const props = defineProps<{
  lf?: LogicFlow;
  data: LogicFlow.NodeData | LogicFlow.EdgeData;
  settingData: {
    indicatorId: any;
    ids: any[];
  };
}>();

const form = ref({
  publicDimensionList: [] as IndciatorDimension[],
  timePeriodTableData: [] as IndciatorTimePeriodListResponse[],
  selectedDimensionIds: [] as number[],
  selectedTimeIds: [] as number[],
});

const indicatorIds = reactive<IndicatorIds>({});
// 存储选中数据的字段名，而非行索引
const selectedTimeIds = ref<number[]>([]);
const selectedDimensionIds = ref<number[]>([]);
const tableRefTime = ref();
const tableRefDimension = ref();

watch(
  () => props.data,
  (newVal) => {
    const { publicDimensionList, timePeriodTableData, selectedDimensionIds, selectedTimeIds } =
      newVal.properties as MyLogicFlowPropertiesType;
    form.value = {
      publicDimensionList: publicDimensionList || [],
      timePeriodTableData: timePeriodTableData || [],
      selectedDimensionIds: selectedDimensionIds || [],
      selectedTimeIds: selectedTimeIds || [],
    };
    props.lf?.setProperties(newVal.id, {
      ...form.value,
    });
  },
  {
    immediate: true,
  }
);

const handleQuery = async () => {
  indicatorIds.indicatorIds = props.settingData._value.ids;
  await IndicatorThemeTableAPI.TimePeriodList(indicatorIds).then((data) => {
    form.value.timePeriodTableData = data;
  });
  await IndicatorThemeTableAPI.DimensionList(indicatorIds).then((data) => {
    form.value.publicDimensionList = data.publicDimensionList!;
  });
  echoSelection();
};

// 处理勾选框变化
const handleTimeSelectionChange = (selectedItems: any) => {
  form.value.selectedTimeIds = selectedItems.map((item: any) => item.id);
  props.lf?.setProperties(props.data.id, {
    selectedTimeIds: form.value.selectedTimeIds,
  });
};

const handleDimensionSelectChange = (selectedItems: any) => {
  form.value.selectedDimensionIds = selectedItems.map((item: any) => item.id);
  props.lf?.setProperties(props.data.id, {
    selectedDimensionIds: form.value.selectedDimensionIds,
  });
};

const toggleSelectionDimension = (rows?: IndciatorDimension[], ignoreSelectable?: boolean) => {
  if (rows) {
    rows.forEach((row) => {
      tableRefDimension.value!.toggleRowSelection(row, undefined, ignoreSelectable);
    });
  } else {
    tableRefDimension.value!.clearSelection();
  }
};

const toggleSelectionTime = (
  rows?: IndciatorTimePeriodListResponse[],
  ignoreSelectable?: boolean
) => {
  if (rows) {
    rows.forEach((row) => {
      tableRefTime.value!.toggleRowSelection(row, undefined, ignoreSelectable);
    });
  } else {
    tableRefTime.value!.clearSelection();
  }
};

// 实现勾选的回显效果
const echoSelection = () => {
  if (tableRefDimension.value && form.value.publicDimensionList) {
    const selectedRows = form.value.publicDimensionList.filter((row: any) =>
      form.value.selectedDimensionIds.includes(row.id)
    );
    toggleSelectionDimension(selectedRows);
  }
  if (tableRefTime && form.value.timePeriodTableData) {
    const selectedRows = form.value.timePeriodTableData.filter((row: any) =>
      form.value.selectedTimeIds.includes(row.id)
    );
    toggleSelectionTime(selectedRows);
  }
};

// const saveData = () => {
//   if (form.value.timePeriodTableData.length != 0 && selectedTimeIds.value.length === 0) {
//     ElMessage.warning("请选择数据期列");
//     return;
//   } else if (
//     form.value.publicDimensionList.length != 0 &&
//     selectedDimensionIds.value.length === 0
//   ) {
//     ElMessage.warning("请选择维度");
//   } else {
//     const selectTimeIds = form.value
//       .timePeriodTableData!.filter((row: any) => selectedTimeIds.value.includes(row.id))
//       .map((row) => ({
//         id: row.id,
//       }));
//     const selectDimensionIds = form.value
//       .publicDimensionList!.filter((row: any) => selectedDimensionIds.value.includes(row.id))
//       .map((row) => ({
//         id: row.id,
//       }));
//     // 手动出发数据更新
//     form.value = {
//       ...form.value,
//       publicDimensionList: form.value.publicDimensionList!.map((row: any) => {
//         const isSelected = selectedDimensionIds.value.includes(row.id);
//         return {
//           ...row,
//           // 根据选择状态更新字段，示例
//           isSelected: isSelected,
//         };
//       }),
//       timePeriodTableData: form.value.timePeriodTableData!.map((row: any) => {
//         const isSelected = selectedTimeIds.value.includes(row.id);
//         return {
//           ...row,
//           isSelected: isSelected,
//         };
//       }),
//     };
//     props.lf?.setProperties(props.data.id, {
//       ...form.value,
//     });
//     ElMessage.success("数据已保存");
//   }
// };

onMounted(() => {
  if (props.settingData._value.ids) {
    handleQuery();
  }
});
</script>
<style lang="scss" scoped>
.setting-title {
  justify-content: center;
  padding: 10px 0;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  border-bottom: 1px solid #e9e9e9;
}

.setting-item {
  .setting-item-title {
    padding: 10px 0;
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: bold;
    border-bottom: 1px solid #e9e9e9;
  }

  .table_infinite_list {
    height: calc(100% - 100px);
    padding: 0;
    margin: 0;
    list-style: none;
  }

  .table_infinite_list .table_infinite_list_item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 20px;
    // background: var(--el-color-primary-light-9);
    margin: 10px;
    // color: var(--el-color-primary);
  }

  .table_infinite_list .table_infinite_list_item + .list-item {
    margin-top: 10px;
  }
}
</style>
